#include "topcvt_dictor.hpp"

#include "topcvt_logutil.hpp"
#include "topcvt_string.hpp"

#include "topcvt_common.hpp"

const char* defaultDictFileName = "dict.xml"; 

namespace topcvt
{

    Dictor::Dictor()
    {
        try{
            topcvt_string::format(m_dictFile,"%s/xml/%s",getenv("HOME"),defaultDictFileName);
            loadDict();
        }catch(exception e){
            TLOG_ERROR("loading dictFile execption:%s",e.what());
        }
    }

    Dictor::Dictor(const string& dictFile)
    {
        try{
            if(dictFile.empty()){
                //topcvt_string::format(m_dictFile,"%s/xml/%s",getenv("HOME"),defaultDictFileName);
            } else {
                m_dictFile = dictFile;
            }
            loadDict();
        } catch(exception e){
            TLOG_ERROR("loading dictFile execption:%s",e.what());
        }
    }    

    void Dictor::setDictFile(const string& dictFile)
    {
        if(!dictFile.empty())
            m_dictFile = dictFile;
    }

    const string& Dictor::getDictFile() const
    {
        return m_dictFile;
    }  

    int Dictor::loadDict( )
    {
        if(m_dictFile.empty()){
            return -1;
        }
        pugi::xml_parse_result result;
        result = m_doc.load_file(m_dictFile.c_str(), pugi::parse_default);
        if(result.status != 0 )
        {
            TLOG_WARN("Load dictfile [%s] [%s]",m_dictFile.c_str(),xmlStatusInfo(result.status).c_str());
            return -1;
        }	        
    }

    string Dictor::getDictValue(const string& sDictId, const string& sSrcValue )
    {
        if(m_doc.empty() ){
            return sSrcValue;
        }

        pugi::xpath_node xpath_node;
        string case_xpath,default_xpath;
        topcvt_string::format(case_xpath,"/root/dict[@id='%s']/case[@srcValue='%s']",sDictId.c_str(),sSrcValue.c_str());
        topcvt_string::format(default_xpath,"/root/dict[@id='%s']/default",sDictId.c_str());
        pugi::xpath_node_set xpath_nodes = m_doc.select_nodes(case_xpath.c_str());
        if(xpath_nodes.size() == 0)
        {
            TLOG_DEBUG("select_nodes[%s] not found",case_xpath.c_str());
            xpath_nodes = m_doc.select_nodes(default_xpath.c_str());
            if(xpath_nodes.size() == 0)
            {
                TLOG_DEBUG("select_nodes[%s] not found",default_xpath.c_str());
                return sSrcValue;
            }
            TLOG_DEBUG("select_nodes[%s] found",default_xpath.c_str());
        }
        else
        {
            TLOG_TRACE("select_nodes[%s] found",case_xpath.c_str());
        }
        xpath_node = xpath_nodes.first();
        return xpath_node.node().attribute("destValue").value();       
    }
}